/*
 * Aboboo Android
 * Copyright (C) 2012 www.aboboo.com
 * 
 */
package com.aboboo.android.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import android.view.LayoutInflater;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.BaseAdapter;
import android.widget.ViewFlipper;

import com.aboboo.android.R;
import com.aboboo.android.json.ParseJsonInfo;
import com.aboboo.android.json.JsonCourseware;
import com.aboboo.android.constant.AbobooConstant;
import com.aboboo.android.download.FileUtils;

import com.aboboo.android.database.DwCourseware;
import com.aboboo.android.database.AbobooDBService;

import com.aboboo.android.activity.StudyingNowActivity;
import com.aboboo.android.constant.AppConstant;

/**
 * 显示指定课件组的课件列表,下载页面需要重新改进
 * 
 * @author fangpeng
 * @version 2013-01-14
 * 
 */
public class CoursewaresListActivity extends Activity {

	public final static String ACTIVITY_TAG = "CoursewaresListActivity";

	public final static String PAR_KEY = "com.aboboo.android.activity.CoursewaresListActivity.par_key";

	// 进度条提示
	private ProgressDialog pDialog = null;

	private String group_id;

	private String courseGroupName;

	private String courseGroupUrl;

	// 课件组名称
	private TextView coursewareGroupNameTextView;

	private ListView coursewaresListView;

	// 适配器
	private CoursewaresListViewAdapter adapter;

	private AbobooDBService dbService = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.coursewares_list);

		Log.i(ACTIVITY_TAG, "Running CoursewaresListActivity");

		getCourseGroupInfo();
		initDBService();
		findViews();
		setListView();
	}

	/**
	 * 初始化数据库服务
	 */
	private void initDBService() {
		dbService = new AbobooDBService(CoursewaresListActivity.this);
	}

	/**
	 * 得到课件组的相关信息
	 */
	private void getCourseGroupInfo() {
		Intent intent = getIntent();
		this.courseGroupName = intent.getStringExtra("courseGroupName");
		this.courseGroupUrl = intent.getStringExtra("courseGroupUrl");
		this.group_id = intent.getStringExtra("group_id");
	}

	private void findViews() {
		coursewareGroupNameTextView = (TextView) findViewById(R.id.courseware_group_name);
		coursewaresListView = (ListView) findViewById(R.id.coursewares_listview);
	}

	private void setListView() {
		coursewareGroupNameTextView.setText(this.courseGroupName);
		pDialog = ProgressDialog.show(CoursewaresListActivity.this, "",
				"正在获取课件信息， 请稍候...", true, true);
		new Thread(new Runnable() {

			@Override
			public void run() {
				final ArrayList<JsonCourseware> coursewaresList = ParseJsonInfo
						.getCoursewares(CoursewaresListActivity.this.courseGroupUrl);
				final ArrayList<DwCourseware> dbDwCoursewareList = dbService
						.cwQueryByGroupId(group_id);
				CoursewaresListActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						if (!coursewaresList.isEmpty()) {
							ArrayList<HashMap<String, Object>> coursewaresData = getCoursewaresData(coursewaresList);
							adapter = new CoursewaresListViewAdapter(
									CoursewaresListActivity.this,
									coursewaresData, dbDwCoursewareList);
							coursewaresListView.setAdapter(adapter);
						} else {
							// 提示加载课件信息失败
						}
						pDialog.dismiss();
					}
				});
			}
		}).start();

	}

	private ArrayList<HashMap<String, Object>> getCoursewaresData(
			final ArrayList<JsonCourseware> coursewaresList) {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for (JsonCourseware courseware : coursewaresList) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("id", courseware.getId());
			map.put("group_id", group_id);
			map.put("group_name", courseGroupName);
			map.put("modified", courseware.getModified());
			map.put("name", courseware.getName().trim());
			map.put("img_url", courseware.getImg_url());
			map.put("download_url", courseware.getDownload_url());
			map.put("class1", courseware.getClass1());
			map.put("class2", courseware.getClass2());
			map.put("filesize", courseware.getFilesize());
			map.put("filesizeForM",
					formatCoursewareFileSize(courseware.getFilesize()));
			data.add(map);
		}
		return data;
	}

	/**
	 * 转化课件文件大小
	 * 
	 * @param fileSize
	 * @return
	 */
	private String formatCoursewareFileSize(int fileSize) {
		DecimalFormat df = new DecimalFormat("0.0");
		return df.format(fileSize / (1024 * 1024.0));
	}

	/**
	 * 封装课件展示信息
	 * 
	 * @author fangpeng
	 * 
	 */
	private final class CoursewareViewHolder {
		public TextView name;
		public TextView modified;
		public TextView img_url;
		public TextView download_url;
		public TextView class1;
		public TextView class2;
		public TextView filesize;
		public ImageButton download_btn;
		public ProgressBar downloadProgressBar;
		private ImageButton dw_play_btn;

	}

	/**
	 * 课件信息列表适配器
	 * 
	 * @author fangpeng
	 * 
	 */
	private class CoursewaresListViewAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		private ArrayList<HashMap<String, Object>> coursewaresData;

		private ArrayList<DwCourseware> dbDwCoursewareList;

		private HashMap<Integer, Integer> dwButtonState = new HashMap<Integer, Integer>();

		// 下载课件在数据库中的保存路径
		private HashMap<Integer, String> dwCoursewareSavePath = new HashMap<Integer, String>();

		// 下载保存后的课件名称
		private HashMap<Integer, String> dwCoursewareSaveName = new HashMap<Integer, String>();
		// 下载进度
		private HashMap<Integer, Integer> dwProgress = new HashMap<Integer, Integer>();

		// 文件大小，用于设置进度条的总进度
		private HashMap<Integer, Integer> dwpgBarMaxValue = new HashMap<Integer, Integer>();

		// 进度条状态
		private HashMap<Integer, Integer> pgBarState = new HashMap<Integer, Integer>();

		// 课件是否已经下载完成
		private HashMap<Integer, Boolean> dwCompleted = new HashMap<Integer, Boolean>();

		// 应保存至数据库
		private HashMap<Integer, Boolean> hasSavedIntoDb = new HashMap<Integer, Boolean>();

		private HashMap<Integer, Integer> dwPlayButtonState = new HashMap<Integer, Integer>();

		public CoursewaresListViewAdapter(Context context,
				ArrayList<HashMap<String, Object>> coursewaresData,
				ArrayList<DwCourseware> dbDwCoursewareList) {
			inflater = LayoutInflater.from(context);
			this.coursewaresData = coursewaresData;
			this.dbDwCoursewareList = dbDwCoursewareList;
			initWidgetState();
		}

		public void initWidgetState() {
			final int size = coursewaresData.size();
			if (dbDwCoursewareList.isEmpty()) {
				// 数据库中没有该课件组已经下载的课件信息
				for (int i = 0; i < size; i++) {
					dwButtonState.put(i, View.VISIBLE);
					dwCoursewareSavePath.put(i, "");
					dwCoursewareSaveName.put(i, "");
					pgBarState.put(i, View.GONE);
					dwProgress.put(i, 0);
					dwpgBarMaxValue.put(i, 0);
					dwCompleted.put(i, false);
					hasSavedIntoDb.put(i, false);
					dwPlayButtonState.put(i, View.GONE);
				}
			} else {
				for (int i = 0; i < size; i++) {
					final HashMap<String, Object> courseware = (HashMap<String, Object>) coursewaresData
							.get(i);
					final int coursewareId = ((Integer) courseware.get("id"))
							.intValue();
					boolean hasDownload = false;
					String cwSavePath = "";
					String cwSaveName = "";
					int fileLength = 0;
					for (DwCourseware dbCourseware : dbDwCoursewareList) {
						if (dbCourseware.getCourseware_id() == coursewareId) {
							hasDownload = true;
							cwSavePath = dbCourseware.getSd_filePath();
							cwSaveName = dbCourseware.getSd_fileName();
							fileLength = dbCourseware.getFileLength();
							break;
						}
					}

					if (hasDownload) {
						dwButtonState.put(i, View.GONE);
						dwCoursewareSavePath.put(i, cwSavePath);
						dwCoursewareSaveName.put(i, cwSaveName);
						pgBarState.put(i, View.GONE);
						dwProgress.put(i, 0);
						dwpgBarMaxValue.put(i, fileLength);
						dwCompleted.put(i, true);
						hasSavedIntoDb.put(i, true);
						dwPlayButtonState.put(i, View.VISIBLE);
					} else {
						dwButtonState.put(i, View.VISIBLE);
						dwCoursewareSavePath.put(i, "");
						dwCoursewareSaveName.put(i, "");
						pgBarState.put(i, View.GONE);
						dwProgress.put(i, 0);
						dwpgBarMaxValue.put(i, 0);
						dwCompleted.put(i, false);
						hasSavedIntoDb.put(i, false);
						dwPlayButtonState.put(i, View.GONE);
					}
				}
			}
		}

		@Override
		public int getCount() {
			return coursewaresData.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final CoursewareViewHolder holder;
			final int p = position;
			if (convertView == null) {
				holder = new CoursewareViewHolder();
				convertView = this.inflater.inflate(R.layout.courseware_item,
						null);
				holder.name = (TextView) convertView
						.findViewById(R.id.courseware_name);
				holder.modified = (TextView) convertView
						.findViewById(R.id.courseware_modified);
				holder.class2 = (TextView) convertView
						.findViewById(R.id.courseware_class2);
				holder.filesize = (TextView) convertView
						.findViewById(R.id.courseware_size);
				holder.download_btn = (ImageButton) convertView
						.findViewById(R.id.courseware_download_btn);
				holder.downloadProgressBar = (ProgressBar) convertView
						.findViewById(R.id.courseware_download_progressBar);
				holder.dw_play_btn = (ImageButton) convertView
						.findViewById(R.id.courseware_download_play_btn);
				convertView.setTag(holder);
			} else {
				holder = (CoursewareViewHolder) convertView.getTag();
			}

			final HashMap<String, Object> coursewareMap = coursewaresData
					.get(position);

			if (coursewareMap != null) {
				holder.name.setText((String) coursewareMap.get("name"));
				holder.class2.setText((String) coursewareMap.get("class2"));
				holder.modified.setText((String) coursewareMap.get("modified"));
				holder.filesize.setText((String) coursewareMap
						.get("filesizeForM") + "M");
				holder.download_btn.setVisibility(dwButtonState.get(position));
				if (!(holder.download_btn.getVisibility() == View.GONE)) {
					holder.download_btn
							.setBackgroundResource(R.drawable.ic_download);

					holder.download_btn
							.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									dwButtonState.put(p, View.GONE);
									holder.download_btn
											.setVisibility(View.GONE);
									pgBarState.put(p, View.VISIBLE);
									holder.downloadProgressBar
											.setVisibility(View.VISIBLE);
									// 线程下载课件到SD卡
									new Thread(new CoursewareDownloadYhread(
											coursewareMap, p)).start();
								}
							});
				}
				holder.downloadProgressBar.setVisibility(pgBarState
						.get(position));
				holder.downloadProgressBar
						.setMax(dwpgBarMaxValue.get(position));
				holder.downloadProgressBar
						.setProgress(dwProgress.get(position));
				holder.dw_play_btn.setVisibility(dwPlayButtonState
						.get(position));
				if (!(holder.dw_play_btn.getVisibility() == View.GONE)) {
					// 设置播放按钮
					holder.dw_play_btn
							.setBackgroundResource(R.drawable.ic_dw_play);
					holder.dw_play_btn
							.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									// 播放当前选中的课件, activity 跳转
									DwCourseware dbCourseware = dbService
											.cwQueryById((Integer) coursewareMap
													.get("id"));
									// Log.i("学习课件", (Integer)
									// coursewareMap.get("id")+
									// coursewareMap.get("name").toString());
									if (dbCourseware != null) {
										// 更新最后学习时间
										dbService.cwUpdate(
												(Integer) coursewareMap
														.get("id"), System
														.currentTimeMillis());
										setSelectorBackgroundAndSwitchToStudying(dbCourseware);
									}
								}
							});
				}
				// 已经下载完成
				if (dwCompleted.get(position)) {
					pgBarState.put(p, View.GONE);
					holder.downloadProgressBar.setVisibility(View.GONE);
					// 显示播放按钮
					dwPlayButtonState.put(p, View.VISIBLE);
					holder.dw_play_btn.setVisibility(View.VISIBLE);
					// 保存下载的课件信息到数据库
					if (!hasSavedIntoDb.get(position)) {
						DwCourseware courseware = new DwCourseware();
						courseware.setCourseware_id((Integer) coursewareMap
								.get("id"));
						courseware.setGroup_id(Integer
								.parseInt((String) coursewareMap
										.get("group_id")));
						courseware.setGroup_name((String) coursewareMap
								.get("group_name"));
						courseware.setName((String) coursewareMap.get("name"));
						courseware.setClass1((String) coursewareMap
								.get("class1"));
						courseware.setClass2((String) coursewareMap
								.get("class2"));
						courseware.setFileLength(dwpgBarMaxValue.get(position));
						courseware.setDownload_url((String) coursewareMap
								.get("download_url"));
						courseware.setSd_filePath(dwCoursewareSavePath
								.get(position));
						courseware.setSd_fileName(dwCoursewareSaveName
								.get(position));
						courseware.setDw_date(System.currentTimeMillis());
						courseware.setRecent_study_date(0);
						hasSavedIntoDb.put(p, true);
						dbService.cwInsert(courseware);
					}
				}
			}

			return convertView;
		}

		/**
		 * 
		 * 多线程课件下载类
		 * 
		 */
		private final class CoursewareDownloadYhread implements Runnable {

			// 课件信息
			private HashMap<String, Object> courseware;

			// 课件在listView中的位置
			private int pos;

			private HttpURLConnection urlConnection;

			private InputStream inputstream;

			private FileOutputStream outputstream;

			// 已经下载的文件大小
			private int downloadedSize = 0;

			// HTTP请求获得的文件大小
			private int httpFileLength = 0;

			private FileUtils fileutil;

			public CoursewareDownloadYhread(HashMap<String, Object> courseware,
					int pos) {
				this.courseware = courseware;
				this.pos = pos;
				fileutil = new FileUtils();
			}

			@Override
			public void run() {
				try {
					byte[] buffer = new byte[4 * 1024];
					String saveFileName = fileutil.getFileNameFromUrl(
							getJSONDownloadUrl(), getCoursewareName());
					fileutil.createSDDir(getClass1(), getClass2());
					File file = fileutil.createSDFile(getClass1(), getClass2(),
							saveFileName);
					initUrlConnect();
					outputstream = new FileOutputStream(file);
					dwCoursewareSavePath.put(pos, file.getPath());
					dwCoursewareSaveName.put(pos, saveFileName);
					dwpgBarMaxValue.put(pos, httpFileLength);
					int count;
					while ((count = inputstream.read(buffer)) != -1) {
						downloadedSize += count;
						// 更新进度条的进度值
						dwProgress.put(pos, downloadedSize);

						outputstream.write(buffer, 0, count);

						Message message = new Message();
						message.what = 1;
						handler.sendMessage(message);
					}
					outputstream.flush();
					// 已经下载完成改变状态
					dwCompleted.put(pos, true);
				} catch (Exception e) {
					Log.i(ACTIVITY_TAG + "下载课件出错" + getCoursewareName(), e
							.getMessage().toString());
				} finally {
					try {
						inputstream.close();
						outputstream.close();
					} catch (IOException e) {
						Log.i(ACTIVITY_TAG + "下载课件关闭文件流错误"
								+ getCoursewareName(), e.getMessage()
								.toString());
					}
				}
			}

			/**
			 * 初始化下载连接
			 */
			private void initUrlConnect() {
				try {
					URL url = new URL(getServerCoursewareDownloadUrl());
					urlConnection = (HttpURLConnection) url.openConnection();
					if (urlConnection.getReadTimeout() >= 5) {
						Log.i(ACTIVITY_TAG + "下载课件"
								+ getServerCoursewareDownloadUrl(), "连接服务器超时");
						return;
					}
					inputstream = urlConnection.getInputStream();
					httpFileLength = urlConnection.getContentLength();

				} catch (MalformedURLException e) {
					Log.i(ACTIVITY_TAG + "远程地址下载课件出错" + getCoursewareName(), e
							.getMessage().toString());
				} catch (IOException e) {
					Log.i(ACTIVITY_TAG + "远程地址下载课件出错" + getCoursewareName(), e
							.getMessage().toString());
				}
			}

			/**
			 * 得到么见名称
			 * 
			 * @return
			 */
			private final String getCoursewareName() {
				return (String) courseware.get("name");
			}

			/**
			 * 得到jSON中间数据课件下载的地址
			 * 
			 * @return
			 */
			private final String getJSONDownloadUrl() {
				return (String) courseware.get("download_url");
			}

			/**
			 * 得到课件的服务器下载地址
			 * 
			 * @return
			 */
			private final String getServerCoursewareDownloadUrl() {
				return AbobooConstant.ABOBOO_URL + getJSONDownloadUrl();
			}

			/**
			 * 得到课件文件的大小
			 * 
			 * @return
			 */
			private final int getCoursewareFileSize() {
				return ((Integer) courseware.get("filesize")).intValue();
			}

			/**
			 * 得到课件一级分类
			 * 
			 * @return
			 */
			private final String getClass1() {
				return ((String) courseware.get("class1")).trim().replace(" ",
						"");
			}

			/**
			 * 得到课件二级分类
			 * 
			 * @return
			 */
			private final String getClass2() {
				return ((String) courseware.get("class2")).trim().replace(" ",
						"");
			}

		}

	}

	/**
	 * 课件下载消息处理器，用于更新进度条
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// super.handleMessage(msg);
			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				default:
					break;
				}
			}
		}

	};

	/**
	 * 设置menuGridView背景颜色,跳转学习界面
	 */
	private void setSelectorBackgroundAndSwitchToStudying(
			DwCourseware dbCourseware) {

		// 跳转播放界面
		AbobooActivity abobooActivity = (AbobooActivity) CoursewaresListActivity.this
				.getParent();
		GridView menuGridView = abobooActivity.getMenuGridView();
		final int count = menuGridView.getChildCount();
		for (int i = 0; i < count; i++) {
			menuGridView.getChildAt(i).setBackgroundDrawable(null);
		}
		menuGridView.getChildAt(AppConstant.STUDYING_NOW_ACTIVITY_INDEX)
				.setBackgroundResource(R.drawable.title_bg);
		abobooActivity
				.setClickPosition(AppConstant.STUDYING_NOW_ACTIVITY_INDEX);

		ViewFlipper flipper = abobooActivity.getViewFlipper();
		flipper.removeAllViews();

		Intent intent = new Intent(CoursewaresListActivity.this,
				StudyingNowActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		Bundle bundle = new Bundle();
		bundle.putParcelable(PAR_KEY, dbCourseware);
		intent.putExtras(bundle);

		Window activity = abobooActivity.getLocalActivityManager()
				.startActivity(CoursewaresListActivity.ACTIVITY_TAG, intent);
		flipper.addView(activity.getDecorView());

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return getParent().onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
